/*
 * Server.cpp
 *
 *  Created on: Nov 6, 2012
 *      Author: root
 */

#include "Server.h"

#include "PlayerSystem.h"

Server::Server()
{
	reg<PlayerSystem>();
}

Server::~Server()
{

}

void Server::init()
{
	for(auto it = _systems.begin(),end = _systems.end();it != end;++it)
	{
		auto temp_sys = *it;

		temp_sys->init();
	}
}


void Server::uninit()
{
	for(auto it = _systems.begin(),end = _systems.end();it != end;++it)
	{
		auto temp_sys = *it;

		temp_sys->uninit();
	}

	_systems.clear();

	for(auto it = _handles.begin(),end = _handles.end();it != end;++it)
	{
		auto temp = it->second;

		delete temp;
	}

	_handles.clear();
}

void Server::handle(const Packet & packet)
{
	int id = packet._id;

	auto it = _handles.find(id);

	if(it == _handles.end())
	{
		return;
	}

	Handler * func = it->second;

	func->filt(packet);
}

void Server::handle_player(const Handler * handler,const Packet & packet)
{
	const PlayerHandler * player_handler = dynamic_cast<const PlayerHandler *>(handler);

	PlayerPtr player = System<PlayerSystem>()->get_player(packet._pid);

	if(player == NULL)
	{
		return;
	}

	player_handler->call(player,packet);
}

void Server::insert_1(int id, const PacketHandle & func)
{
	Handler * handler = new Handler();

	handler->_filter = func;

	_handles[id] = handler;
}

void Server::insert_2(int id, const PlayerPacketHandle & func)
{
	PlayerHandler * handler = new PlayerHandler();

	handler->_filter = std::bind(&Server::handle_player,this,handler,std::placeholders::_1);

	handler->_handler = func;

	_handles[id] = handler;
}

